package com.android.bhwallet.app.Main.UI;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.bhwallet.R;
import com.android.bhwallet.app.Main.Interface.OnSexClickListener;
import com.android.bhwallet.utils.FileUtil;
import com.android.bhwallet.utils.HttpHelper;
import com.android.bhwallet.utils.MacUtils;
import com.android.bhwallet.utils.UrlConfig;
import com.asuka.android.asukaandroid.AsukaTakePhotoActivity;
import com.asuka.android.asukaandroid.comm.utils.StringUtils;
import com.asuka.android.asukaandroid.http.EGRequestParams;
import com.asuka.android.asukaandroid.widget.pickview.DatePickerPopWin;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;

import java.io.File;

/**
 * @author 蒋冬冬
 * 创建日期：2020/7/20
 * 邮箱：825814902@qq.com
 * 描述：
 */
public class EleOpenActivity extends AsukaTakePhotoActivity {
    private Button open;
    private ImageView head;
    private EditText name;
    private EditText idcard;
    private TextView start_time;
    private TextView end_time;
    private EditText address;
    private ImageView card1;
    private ImageView card2;
    private EditText tel;
    private TextView get_yzm;
    private EditText code;

    private EditText bank_card;
    private TextView job;
    private EditText password1;
    private EditText password2;
    private TextView sex;

    private int clickIndex;
    private String outputPath;
    private String headPath;
    private String cardPath1;
    private String cardPath2;
    private int iSex;

    private String merUserId;
    private String jobId;

    private ImagePicker imagePicker = new ImagePicker();

    private int timeCount = 60;
    private final int TIME_START = 0X01;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case TIME_START:
                    if (timeCount == 0) {
                        get_yzm.setText("获取验证码");
                        get_yzm.setEnabled(true);
                    } else {
                        get_yzm.setText(timeCount + "s");
                        timeCount--;
                        sendEmptyMessageDelayed(TIME_START, 1000);
                    }
                    break;
            }
        }
    };


    @Override
    protected void initView() {
        setContentView(R.layout.activity_ele_open);


        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(false);

        iSex = -1;
        head = findViewById(R.id.head);
        name = findViewById(R.id.name);
        idcard = findViewById(R.id.idcard);
        start_time = findViewById(R.id.start_time);
        end_time = findViewById(R.id.end_time);
        address = findViewById(R.id.address);
        card1 = findViewById(R.id.card1);
        card2 = findViewById(R.id.card2);
        tel = findViewById(R.id.tel);
        get_yzm = findViewById(R.id.get_yzm);
        code = findViewById(R.id.code);

        bank_card = findViewById(R.id.bank_card);
        password1 = findViewById(R.id.password1);
        password2 = findViewById(R.id.password2);
        sex = findViewById(R.id.sex);
        job = findViewById(R.id.job);

        open = findViewById(R.id.open);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            merUserId = bundle.getString("merUserId");
//            jobId = bundle.getString("job_id");
//            job.setText(bundle.getString("job_name"));
        }

        getUserMessage();
        getJob();
    }

    @Override
    protected void initEvent() {
        get_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getYzm();
            }
        });
        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitData();
            }
        });

        job.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(JobListActivity.class, "职业列表", null);
            }
        });

        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickIndex = 0;
                startChooser();
            }
        });

        card1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickIndex = 1;
                startChooser();
            }
        });

        card2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickIndex = 2;
                startChooser();
            }
        });

        sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FileUtil.SexSelectDialog(EleOpenActivity.this, new OnSexClickListener() {
                    @Override
                    public void onClick(int index, String name) {
                        sex.setText(name);
                        iSex = index;
                    }
                });
            }
        });

        start_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerPopWin pop = new DatePickerPopWin(new DatePickerPopWin.Builder(EleOpenActivity.this, new DatePickerPopWin.OnDatePickedListener() {
                    @Override
                    public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                        start_time.setText(dateDesc);
                    }
                }, false));

                pop.showPopWin(EleOpenActivity.this);
            }
        });

        end_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerPopWin pop = new DatePickerPopWin(new DatePickerPopWin.Builder(EleOpenActivity.this, new DatePickerPopWin.OnDatePickedListener() {
                    @Override
                    public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                        end_time.setText(dateDesc);
                    }
                }, true));
                pop.showPopWin(EleOpenActivity.this);
            }
        });
    }

    @Override
    protected void oberserMsg(String type, JSONObject object) {

    }

    private void upPic(final String path) {
        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("file", new File(path));
        HttpHelper.post(this, UrlConfig.UP_PIC, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                JSONObject data = JSON.parseObject(str);
                Bitmap bp = BitmapFactory.decodeFile(path);
                switch (clickIndex) {
                    case 0:
                        headPath = data.getString("filePath");
                        head.setImageBitmap(bp);
                        //ImageUtil.ShowIamge(head, UrlConfig.BASE_IMAGE_URL +"/walletadmin"+ headPath);
                        break;
                    case 1:
                        cardPath1 = data.getString("filePath");
                        card1.setImageBitmap(bp);
                        //ImageUtil.ShowIamge(card1, UrlConfig.BASE_IMAGE_URL +"/walletadmin"+ cardPath1);
                        break;
                    case 2:
                        cardPath2 = data.getString("filePath");
                        card2.setImageBitmap(bp);
                        //ImageUtil.ShowIamge(card2, UrlConfig.BASE_IMAGE_URL +"/walletadmin"+ cardPath2);
                        break;
                }
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    private void getYzm() {
        final String strTel = tel.getText().toString().trim();
        if (StringUtils.isEmpty(strTel)) {
            showWarning("请输入手机号码");
            return;
        }

        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("mobilePhone", strTel);
        HttpHelper.post(this, UrlConfig.ELE_GET_CODE, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                showSuccess("验证码已发送，请注意查收");
                timeCount = 60;
                handler.sendEmptyMessageDelayed(TIME_START, 1000);
                get_yzm.setEnabled(false);
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    private void getJob(){
        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("merUserId",merUserId);
        HttpHelper.postNoProcess(this, UrlConfig.GET_JOB, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                JSONObject object = JSON.parseObject(str);
                jobId = object.getString("currentWork");
                job.setText(object.getString("workName"));
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    private void commitData() {
        if (StringUtils.isEmpty(headPath)) {
            showWarning("请拍摄人脸");
            return;
        }
        final String strName = name.getText().toString();
        if (StringUtils.isEmpty(strName)) {
            showWarning("请输入姓名");
            return;
        }

        final String strIdCard = idcard.getText().toString().trim();
        if (StringUtils.isEmpty(strIdCard)) {
            showWarning("请输入身份证号");
            return;
        }

        final String strStartTime = start_time.getText().toString().trim();
        if (StringUtils.isEmpty(strStartTime)) {
            showWarning("请选择身份证签发日期");
            return;
        }

        final String strEndTime = end_time.getText().toString().trim();
        if (StringUtils.isEmpty(strEndTime)) {
            showWarning("请选择身份证到期日期");
            return;
        }

        final String strAddress = address.getText().toString().trim();
        if (StringUtils.isEmpty(strAddress)) {
            showWarning("请输入户籍地址");
            return;
        }

        if (StringUtils.isEmpty(cardPath1)) {
            showWarning("请上传身份证正面照片");
            return;
        }
        if (StringUtils.isEmpty(cardPath2)) {
            showWarning("请上传身份证背面照片");
            return;
        }

        final String strTel = tel.getText().toString().trim();
        if (StringUtils.isEmpty(strTel)) {
            showWarning("请输入手机号码");
            return;
        }

        String strCode = code.getText().toString().trim();
        if (StringUtils.isEmpty(strCode)) {
            showWarning("请输入验证码");
            return;
        }

        final String strBackCard = bank_card.getText().toString();
        if (StringUtils.isEmpty(strBackCard)) {
            showWarning("请输入银行卡号");
            return;
        }

        final String strPassword1 = password1.getText().toString().trim();
        if (StringUtils.isEmpty(strPassword1)) {
            showWarning("请输入交易密码");
            return;
        }

        String strPassword2 = password2.getText().toString().trim();
        if (StringUtils.isEmpty(strPassword2)) {
            showWarning("请输入确认密码");
            return;
        }

        if (!strPassword1.equals(strPassword2)) {
            showWarning("两次密码不一致，请确认后重新输入");
            return;
        }

        if (iSex == -1) {
            showWarning("请选择性别");
            return;
        }

        if (StringUtils.isEmpty(jobId)) {
            showWarning("请输入职业");
            return;
        }
        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("acctNo", strBackCard);
        para.addBodyParameter("certLostDate", strEndTime);
        para.addBodyParameter("certNo", strIdCard);
        para.addBodyParameter("certVisaDate", strStartTime);
        para.addBodyParameter("eleAddress", strAddress);
        para.addBodyParameter("eleCustomerName", strName);
        para.addBodyParameter("eleSex", iSex + "");
        para.addBodyParameter("idImgBack", cardPath2);
        para.addBodyParameter("idImgFront", cardPath1);
        para.addBodyParameter("imgBase", headPath);
        para.addBodyParameter("merUserId", merUserId);
        para.addBodyParameter("mobilePhone", strTel);
        para.addBodyParameter("passWord", strPassword1);
        para.addBodyParameter("verifyNo", strCode);
        para.addBodyParameter("taxFlag", "1");
        para.addBodyParameter("workType", jobId);
        para.addBodyParameter("mac", MacUtils.getMacAddress(this));
        para.addBodyParameter("clientId", MacUtils.getIpAddress(this));

        HttpHelper.post(this, UrlConfig.OPEN_ELE, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                showSuccess("电子钱包开通成功");
                sendObseverMsg("update_user", new JSONObject());
                finish();
            }

            @Override
            public void complete(String str) {

            }
        });


    }

    private void getUserMessage() {
        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("merUserId", merUserId);
        HttpHelper.post(this, UrlConfig.WALLET_OPEN_DETAIL, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                JSONObject object = JSON.parseObject(str);
                JSONObject user = object.getJSONObject("user");
                name.setText(user.getString("customerName"));
                tel.setText(user.getString("mobilePhone"));
                idcard.setText(user.getString("certNo"));
                bank_card.setText(user.getString("acctNo"));
//                String supplyInfoUrl = user.getString("supplyInfoUrl");
//                if (!StringUtils.isEmpty(supplyInfoUrl)) {
//                    try {
//                        String url = URLDecoder.decode(supplyInfoUrl, "utf-8");
//                        Uri uri = Uri.parse(url);
//                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                        startActivity(intent);
//                        showWarning("请先补录信息");
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }
//                }
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    private void startChooser() {

        imagePicker.startChooser(this, new ImagePicker.Callback() {
            // 选择图片回调
            @Override
            public void onPickImage(Uri imageUri) {
                upPic(getPathFromUri(EleOpenActivity.this, imageUri));

            }

            // 裁剪图片回调
            @Override
            public void onCropImage(Uri imageUri) {

            }

            // 自定义裁剪配置
            @Override
            public void cropConfig(CropImage.ActivityBuilder builder) {

            }

            // 用户拒绝授权回调
            @Override
            public void onPermissionDenied(int requestCode, String[] permissions,
                                           int[] grantResults) {
            }
        });
    }

    @SuppressLint("NewApi")
    public static String getPathFromUri(final Context context, final Uri uri) {
        if (uri == null) {
            return null;
        }
        // 判斷是否為Android 4.4之後的版本
        final boolean after44 = Build.VERSION.SDK_INT >= 19;
        if (after44 && DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是Android 4.4之後的版本，而且屬於文件URI
            final String authority = uri.getAuthority();
            // 判斷Authority是否為本地端檔案所使用的
            if ("com.android.externalstorage.documents".equals(authority)) {
                // 外部儲存空間
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] divide = docId.split(":");
                final String type = divide[0];
                if ("primary".equals(type)) {
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat("/").concat(divide[1]);
                    return path;
                } else {
                    String path = "/storage/".concat(type).concat("/").concat(divide[1]);
                    return path;
                }
            } else if ("com.android.providers.downloads.documents".equals(authority)) {
                // 下載目錄
                final String docId = DocumentsContract.getDocumentId(uri);
                if (docId.startsWith("raw:")) {
                    final String path = docId.replaceFirst("raw:", "");
                    return path;
                }
                final Uri downloadUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                String path = queryAbsolutePath(context, downloadUri);
                return path;
            } else if ("com.android.providers.media.documents".equals(authority)) {
                // 圖片、影音檔案
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] divide = docId.split(":");
                final String type = divide[0];
                Uri mediaUri = null;
                if ("image".equals(type)) {
                    mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    mediaUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                    return null;
                }
                mediaUri = ContentUris.withAppendedId(mediaUri, Long.parseLong(divide[1]));
                String path = queryAbsolutePath(context, mediaUri);
                return path;
            }
        } else {
            // 如果是一般的URI
            final String scheme = uri.getScheme();
            String path = null;
            if ("content".equals(scheme)) {
                // 內容URI
                path = queryAbsolutePath(context, uri);
            } else if ("file".equals(scheme)) {
                // 檔案URI
                path = uri.getPath();
            }
            return path;
        }
        return null;
    }

    public static String queryAbsolutePath(final Context context, final Uri uri) {
        final String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                return cursor.getString(index);
            }
        } catch (final Exception ex) {
            ex.printStackTrace();
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null){
                    String type = bundle.getString("type");
                    if ("job".equals(type)) {
                        job.setText(bundle.getString("name"));
                        jobId = bundle.getString("id");
                    }
                }

            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}
